import axios from 'axios';
import { useUserStore } from '@/stores/user';

const isDev = import.meta.env.DEV;
const baseURL = isDev ? '' : (import.meta.env.VITE_API_BASE_URL || '');

const http = axios.create({
  baseURL,
  timeout: 30000,
  withCredentials: true
});

// Ensure all requests include cookies
http.defaults.withCredentials = true;

http.interceptors.request.use(config => {
  const userStore = useUserStore();
  if (userStore && userStore.token) {
    config.headers = config.headers || {};
    config.headers.Authorization = `Bearer ${userStore.token}`;
  }
  return config;
});

http.interceptors.response.use(
  response => {
    // 统一处理响应格式
    const { data } = response;
    
    // 检查是否是标准的后端响应格式
    if (data && typeof data === 'object' && 'code' in data) {
      if (data.code === 0) {
        // 成功响应，返回data字段
        return {
          ...response,
          data: data.data
        };
      } else {
        // 业务错误，抛出异常
        const error = new Error(data.msg || '请求失败');
        (error as any).code = data.code;
        (error as any).response = response;
        throw error;
      }
    }
    
    // 非标准格式，直接返回原始响应
    return response;
  },
  error => {
    if (error.response && (error.response.status === 401 || error.response.status === 403)) {
      try {
        const userStore = useUserStore();
        if (userStore && typeof userStore.logout === 'function') {
          userStore.logout();
        }
      } catch (_) {}
    }
    return Promise.reject(error);
  }
);

export default http; 